#!/usr/bin/env python

from cookie_manager import CookieManager
from session import Session
import sys, os

import inspect
class logging_class ():
	LOG_DEBUG = 1
	LOG_INFO  = 2
	LOG_WARN  = 3
	LOG_ERROR = 4
	LOG_CRITICAL = 5

	def __init__ ( self ):
		self.full = 1
		self.level = self.LOG_ERROR

	def debug ( self, txt ):
		self._txt ( self.LOG_DEBUG, txt )

	def info ( self, txt ):
		self._txt ( self.LOG_INFO, txt )

	def warn ( self, txt ):
		self._txt ( self.LOG_WARN, txt )

	def error ( self, txt ):
		self._txt ( self.LOG_ERROR, txt )

	def critical ( self, txt ):
		self._txt ( self.LOG_CRITICAL, txt )

	def _txt ( self, lvl, txt ):
		if self.level > lvl: return
	
		if self.full:
			stk = inspect.stack () [ 2 ]
			fname = "[%s, %s, %s]: " % ( stk [ 1 ], stk [ 2 ], stk [ 3 ] )
		else:
			fname = ""

		sys.stderr.write ( "%s%s\n" % ( fname,  txt ) )

	def getLogger ( self, *args, **kargs ):
		return self

logging = logging_class ()

class PyHP ( object ):
	def __init__ ( self, session_load, session_save, session_delete  ):
		self._headers = {}

		self.get = {}
		self.post = {}

		self.log = logging

		self.session = Session ( self, load = session_load, save = session_save, delete = session_delete )

		self._debug_fname = ""

	def set_debug ( self, fname ):
		self._debug_fname = fname

	def debug ( self, txt ):
		if not self._debug_fname: return
	
		try:
			file ( self._debug_fname, "a" ).write ( txt )
		except:
			pass

	def init ( self, environ ):
		self.env = environ

		self.cookies = CookieManager ( self )
		self.uploads = {}
		self._headers = {}

		self.cookies.read ( environ.get ( "HTTP_COOKIE", "" ) )
		self.return_code = "200 OK"

	def set_header ( self, name, value ):
		self._headers [ name ] = value

	def get_headers ( self ):
		"""
		Prende tutti gli headers di output
		"""

		if 'Content-Type' not in self._headers:
			self._headers [ 'Content-Type' ] = 'text/html'

		headers = []
		for k, v in self._headers.iteritems ():
			headers.append ( ( k, v ) )

		for cook in self.cookies.dump ():
			headers.append ( ( 'Set-Cookie', cook ) )

		return headers
